package com.ruoyi.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.app.service.ChargeOrderService;
import com.ruoyi.common.WxValueConfig;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ShankHandUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.app.*;
import com.ruoyi.system.mapper.CommunityMapper;
import com.ruoyi.system.mapper.CommunityMemberMapper;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.mapper.app.CardMapper;
import com.ruoyi.system.mapper.app.DeptWxInfoMapper;
import com.ruoyi.system.mapper.app.RechargeOrderMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Api(tags = "充值订单相关")
@RestController
@RequestMapping("/order")
public class ChargeOrderController extends BaseController {

    @Autowired
    ChargeOrderService chargeOrderService;
    @Autowired
    WxValueConfig wxPledgeConfig;
    @Autowired
    DeptWxInfoMapper deptWxInfoMapper;

    @Autowired
    RechargeOrderMapper rechargeOrderMapper;
    @Autowired
    ShankHandUtils shankHandUtils;
    @Autowired
    CardMapper cardMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CommunityMemberMapper communityMemberMapper;
    @Autowired
    CommunityMapper communityMapper;

    @ApiOperation("获取集合充值记录")
    @GetMapping("/list")
    public AjaxResult chargeList(){
        startPage();
        return AjaxResult.success(getDataTable(chargeOrderService.chargeList()));
    }

    @ApiOperation(value = "获取充值详情 ",notes = " type 1钱包充值 2包月充值 3电卡充值")
    @GetMapping("/info/{id}")
    public AjaxResult getOrderInfo(@PathVariable Long id, @RequestParam Integer type){
        return AjaxResult.success(chargeOrderService.getOrderInfo(id,type));
    }

    @ApiOperation("获取充电记录")
    @GetMapping("/recharge-list")
    public AjaxResult rechargeList(Long orderId){
        startPage();
        return AjaxResult.success(getDataTable(chargeOrderService.rechargeList(orderId)));
    }

    @ApiOperation(value = "创建钱包支付订单")
    @PostMapping("/create-charge")
    public AjaxResult createChargeOrder(@RequestParam Long communityId,@RequestParam Long chargeOptionId){
        return AjaxResult.success(chargeOrderService.createChargeOrder(communityId,chargeOptionId));
    }

    @ApiOperation(value = "创建电卡支付订单",notes = " ")
    @PostMapping("/create-card")
    public AjaxResult createCardOrder(@RequestParam Long communityId,@RequestParam Long chargeOptionId,
                                      @RequestParam String cardNum){
        return AjaxResult.success(chargeOrderService.createCardChargeOrder(communityId,chargeOptionId,cardNum));
    }

    @ApiOperation(value = "创建包月支付订单",notes = " ")
    @PostMapping("/create-combo")
    public AjaxResult createComboOrder(@RequestParam Long communityId,@RequestParam Long chargeOptionId){
        return AjaxResult.success(chargeOrderService.createComboChargeOrder(communityId,chargeOptionId));
    }


    @ApiOperation("创建充电订单")
    @PostMapping("/create-recharge")
    @RepeatSubmit
    public AjaxResult createRecharge(@RequestParam String deviceNum,@RequestParam Integer chargeTime,@RequestParam Integer socketNo){

        return AjaxResult.success(chargeOrderService.createRecharge(deviceNum,chargeTime,socketNo));
    }

    @ApiOperation(value = "创建临时充电订单",notes = "socketNo 插座编号")
    @PostMapping("/pay/create-recharge")
    @RepeatSubmit
    public AjaxResult createPayRecharge(@RequestParam String deviceNum, @RequestParam BigDecimal chargeMoney,@RequestParam Integer socketNo){

        return AjaxResult.success(chargeOrderService.createPayRecharge(deviceNum,chargeMoney,socketNo));
    }

    @ApiOperation("超时删除订单")
    @DeleteMapping("/del/timeout-recharge")
    public AjaxResult delRecharge(@RequestParam Long orderId){
        chargeOrderService.delRecharge(orderId);
        return AjaxResult.success();
    }


    @RepeatSubmit
    @ApiOperation("手动结束充电订单")
    @PostMapping("/end-recharge")
    public AjaxResult endRecharge(@RequestParam String orderNo) throws InterruptedException {
        RechargeOrder rechargeOrder = rechargeOrderMapper.selectByOrderNo(orderNo);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceError", "0");
        chargeOrderService.endRecharge(orderNo);
        Thread.sleep(5000);
        RechargeOrder rechargeOrder2 = rechargeOrderMapper.selectByOrderNo(orderNo);
        if(rechargeOrder2.getState()!=4 || rechargeOrder2.getOrderState() !=4 ){
            RechargeOrder rechargeOrder1 = new RechargeOrder();
            rechargeOrder1.setId(rechargeOrder.getId());
            rechargeOrder1.setEndCause("6");
            rechargeOrder1.setOrderState(4);
            rechargeOrder1.setState(4);
            rechargeOrder1.setRechargeEndTime(new Date());
            rechargeOrderMapper.updateByPrimaryKeySelective(rechargeOrder1);
            deductMoney(rechargeOrder);
            return AjaxResult.error(jsonObject.toJSONString());
        }

        return AjaxResult.success();
    }

    @RepeatSubmit
    @ApiOperation("下发开门取电池")
    @PostMapping("/open-door/cell-out")
    public AjaxResult openDoorCellOut(@RequestParam String orderNo){
        //chargeOrderService.openDoorCellOut(orderNo);
        return AjaxResult.success();
    }

    @ApiOperation(value = "创建微信预支付订单",notes = "type 1钱包充值 2包月充值 3电卡充值 4临时充电")
    @PostMapping("/create-wx-order")
    public AjaxResult createWxOrder(@RequestParam Long orderId,@RequestParam Integer type,@RequestParam String code,
                                    @RequestParam String appId){
        return AjaxResult.success(chargeOrderService.createWxPayV2(orderId,type,code,appId));
    }


    @ApiIgnore
    @PostMapping("/pay/wx/result")
    public synchronized String PayResult(HttpServletRequest request) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        //sb为微信返回的xml
        Map<String, String> mapResult = WXPayUtil.xmlToMap(sb.toString());
        String[] strings = mapResult.get("attach").split(":");
        log.info("微信推送数据" + mapResult.toString());

        //更改订单状态
        chargeOrderService.wxPayResult(mapResult,strings[0]);

        Map map = new HashMap();
        if (!WXPayUtil.isSignatureValid(mapResult, deptWxInfoMapper.selectByPrimaryKey(Long.valueOf(strings[1])).getWxKey())) {
            log.info("return_code不正确");
            map.put("return_msg", "return_code不正确");
            map.put("return_code", "FAIL");
            String resXml = WXPayUtil.mapToXml(map);
            return resXml;
        }
        if (mapResult.get("result_code").equals("SUCCESS") && mapResult.get("return_code").equals("SUCCESS")) {
            log.info("return_code正确");
            map.put("return_msg", "OK");
            map.put("return_code", "SUCCESS");
            String resXml = WXPayUtil.mapToXml(map);
            return resXml;
        }

        return null;
    }


    private void deductMoney(RechargeOrder rechargeOrder){
        User user = userMapper.selectByPrimaryKey(rechargeOrder.getUserId());
        //余额扣款
        if (rechargeOrder.getPayType() == 1) {
            //订单结束
            Community community = communityMapper.selectByPrimaryKey(rechargeOrder.getCommunityId());
            CommunityMember communityMember = communityMemberMapper.selectByUser(user.getId(), rechargeOrder.getCommunityId());
            //余额通用
            if (StringUtils.isNull(communityMember) || community.getIsBalanceUse() == 1) {
                //扣款
                BigDecimal countMoney = rechargeOrder.getAllMoney();
                log.info("订单金额：" + countMoney);

                List<CommunityMember> communityMembers = communityMemberMapper.getCommunityMembersByOperatorId(user.getId(), rechargeOrder.getOperatorId());
                for (CommunityMember communityMember1 : communityMembers) {

                    if (countMoney.doubleValue() <= communityMember1.getBalance().doubleValue()) {
                        communityMember1.setBalance(communityMember1.getBalance().subtract(countMoney));
                        countMoney = BigDecimal.valueOf(0);
                        log.info("金额小于余额");
                        log.info(communityMember1.getBalance() + "");
                        log.info(communityMember1.getDiscountBalance() + "");
                        log.info(countMoney + "");
                    } else if (countMoney.doubleValue() > communityMember1.getBalance().doubleValue()) {
                        countMoney = countMoney.subtract(communityMember1.getBalance());
                        communityMember1.setBalance(new BigDecimal("0"));
                        log.info("金额大于余额");
                        log.info(communityMember1.getBalance() + "");
                        log.info(communityMember1.getDiscountBalance() + "");
                        log.info(countMoney + "");
                    }
                    if (countMoney.doubleValue() <= communityMember1.getDiscountBalance().doubleValue()) {
                        communityMember1.setDiscountBalance(communityMember1.getDiscountBalance().subtract(countMoney));
                        countMoney = BigDecimal.valueOf(0);
                        log.info("金额小于活动余额");
                        log.info(communityMember1.getBalance() + "");
                        log.info(communityMember1.getDiscountBalance() + "");
                        log.info(countMoney + "");
                    } else if (countMoney.doubleValue() > communityMember1.getDiscountBalance().doubleValue()) {
                        countMoney = countMoney.subtract(communityMember1.getDiscountBalance());
                        communityMember1.setDiscountBalance(new BigDecimal("0"));
                        log.info("金额大于活动余额");
                        log.info(communityMember1.getBalance() + "");
                        log.info(communityMember1.getDiscountBalance() + "");
                        log.info(countMoney + "");
                    }
                    communityMemberMapper.updateByPrimaryKeySelective(communityMember1);
                    if (countMoney.doubleValue() == 0D) {
                        break;
                    }
                }
            }
            // 没开启余额通用
            if (StringUtils.isNotNull(communityMember) &&  community.getIsBalanceUse() == 0) {
                //余额
                if (rechargeOrder.getPayType() == 1) {
                    //扣款
                    BigDecimal orderMoney = rechargeOrder.getAllMoney();
                    log.info("订单金额" + orderMoney.toPlainString());

                    if (orderMoney.doubleValue() <= communityMember.getBalance().doubleValue()) {
                        communityMember.setBalance(communityMember.getBalance().subtract(orderMoney));
                        log.info("真实金额" + communityMember.getBalance().toPlainString());
                    } else if (orderMoney.doubleValue() <= communityMember.getDiscountBalance().doubleValue()) {
                        communityMember.setDiscountBalance(communityMember.getDiscountBalance().subtract(orderMoney));
                        log.info("活动金额" + communityMember.getDiscountBalance().toPlainString());
                    } else  {
                        communityMember.setBalance(communityMember.getBalance().subtract(orderMoney));
                        communityMember.setDiscountBalance(communityMember.getBalance().add(communityMember.getDiscountBalance()));
                        communityMember.setBalance(new BigDecimal("0"));
                    }
                    //余额为负数重置为0
                    if(communityMember.getDiscountBalance().doubleValue()<0){
                        communityMember.setDiscountBalance(new BigDecimal("0"));
                    }
                    if(communityMember.getBalance().doubleValue()<0){
                        communityMember.setBalance(new BigDecimal("0"));
                    }

                    communityMemberMapper.updateByPrimaryKeySelective(communityMember);
                }

            }
        }
        //电卡
        else if (rechargeOrder.getPayType() == 3) {
            Card card = cardMapper.selectByNum(rechargeOrder.getCardNo());
            //扣款
            BigDecimal orderMoney = rechargeOrder.getAllMoney();
            if (orderMoney.doubleValue() <= card.getDiscountsMoney().doubleValue()) {
                card.setDiscountsMoney(card.getDiscountsMoney().subtract(orderMoney));
            } else if (orderMoney.doubleValue() <= card.getMoney().doubleValue()) {
                card.setMoney(card.getMoney().subtract(orderMoney));
            } else  {
                card.setMoney(card.getMoney().subtract(orderMoney));
                card.setDiscountsMoney(card.getDiscountsMoney().add(card.getMoney()));
                card.setMoney(new BigDecimal("0"));
            }
            //余额为负数重置为0
            if(card.getDiscountsMoney().doubleValue()<0){
                card.setDiscountsMoney(new BigDecimal("0"));
            }
            if(card.getMoney().doubleValue()<0){
                card.setMoney(new BigDecimal("0"));
            }
            cardMapper.updateByPrimaryKeySelective(card);
        }
    }


}
